package org.tio.sitexxx.im.server.handler;

import org.tio.core.ChannelContext;
import org.tio.sitexxx.im.common.Command;
import org.tio.sitexxx.im.common.CommandHandler;
import org.tio.sitexxx.im.common.ImPacket;
import org.tio.sitexxx.im.common.MsgModel.KFJOINP2PReq;
import org.tio.sitexxx.im.common.MsgModel.KFP2PNty;
import org.tio.sitexxx.im.common.MsgModel.KFUser;
import org.tio.sitexxx.im.server.Ims;
import org.tio.sitexxx.im.server.utils.ImUtils;
import org.tio.sitexxx.service.model.main.ChatRecordP2p;
import org.tio.sitexxx.service.model.main.Consultant;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.utils.json.Json;

import java.util.List;


@CommandHandler(Command.KF_JOIN_P2P_REQ_)
public class KFJOINP2PHandler_ implements ImServerHandler {
    @Override
    public void handler(ImPacket packet, ChannelContext channelContext, boolean isWebsocket) throws Exception {
        SimpleUser fromUser = ImUtils.getSimpleUser(channelContext);
        KFJOINP2PReq req = Json.toBean(packet.getBodyStr(),KFJOINP2PReq.class);
        System.out.println("uid"+req.getUid());
        List<ChatRecordP2p> recordsP2p = ChatRecordP2p.dao.find("select * from chat_record_p2p where touid = ? and readflag=2 and contenttype>10",req.getUid());//查询用户与顾问之间的未读消息
        if(recordsP2p==null) return;
        for(ChatRecordP2p msg:recordsP2p){//未读消息记录
            int type=msg.getContenttype();
            ImPacket imPacket=null;
            System.out.println("uid:"+msg.getUid());
           if(type==11){
                KFP2PNty nty = getNty(msg);
                imPacket = new ImPacket(Command.KF_P2P_NTY0,nty);
            }else if(type==16){
                KFP2PNty nty = getNty(msg);
                imPacket = new ImPacket(Command.KF_PICTURE_NTY0,nty);
            }else if(type==15){
                KFP2PNty nty = getNty(msg);
                imPacket = new ImPacket(Command.KF_VIDEO_NTY0,nty);
            }else if(type==14){
                KFP2PNty nty = getNty(msg);
                imPacket = new ImPacket(Command.KF_VOICE_NTY0,nty);
            }
            Ims.sendToUser(req.getUid(),imPacket);
        }
    }
    private static KFP2PNty getNty(ChatRecordP2p msg){
        KFUser user;
        Member member=Member.dao.findFirst("select * from member where id=?",msg.getUid());//消息来自member
        if(member==null){
            Consultant consultant=Consultant.dao.findFirst("select * from consultant where id=?",msg.getUid());//消息来自顾问
            user= KFUser.fromConsultant(consultant);
        }else{
            user= KFUser.fromMember(member);
        }
        KFP2PNty nty = new KFP2PNty(msg.getUid(), msg.getTouid(), msg.getId(), msg.getText(), msg.getTime().getTime(),user);
        return nty;
    }
}
